package com.cmall.common.mongo;

import java.util.List;

import org.springframework.data.authentication.UserCredentials;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import com.cmall.common.foundation.util.Page;
import com.mongodb.Mongo;

/**
 * 
 * 数据访问层基础支撑类
 * 
 */
@Service("mongodbBaseDao")
@SuppressWarnings({ "rawtypes", "unchecked" })
public class MongodbBaseDao<T> extends MongoTemplate {

	/**
	 * 未验证此构造函数
	 * 
	 * @param mongoDbFactory
	 */
	public MongodbBaseDao(MongoDbFactory mongoDbFactory) {
		super(mongoDbFactory);
	}

	public MongodbBaseDao(Mongo mongo, String databaseName) {
		super(mongo, databaseName);
	}

	public MongodbBaseDao(Mongo mongo, String databaseName, UserCredentials userCredentials) {
		super(mongo, databaseName, userCredentials);
	}

	/**
	 * 根据分页参数获取此实体的分页信息及实体列表数据
	 * 
	 * @see #queryForPage(int, int, Query, Class, boolean)
	 */
	public Page<T> queryForPage(Query query, Class<?> entityClass) {
		return queryForPage(0, 0, query, entityClass, true);
	}

	/**
	 * 根据分页参数获取此实体的分页信息及实体列表数据
	 * 
	 * @see #queryForPage(int, int, Query, Class, boolean)
	 */
	public Page<T> queryForPage(int currentPage, int pageSize, Query query, Class<?> entityClass) {
		return queryForPage(currentPage, pageSize, query, entityClass, true);
	}

	/**
	 * 根据分页参数获取此实体的分页信息及实体列表数据
	 * 
	 * @param currentPage
	 *            当前页
	 * @param pageSize
	 *            每页条数
	 * @param query
	 *            Query查询条件对象
	 * @param entityClass
	 *            查询实体
	 * @param items
	 *            是否获取查询实体列表
	 * 
	 * @return Page分页实体
	 */
	public Page<T> queryForPage(int currentPage, int pageSize, Query query, Class<?> entityClass, boolean items) {
		if (currentPage == 0) {// 默认当前页为第一页
			currentPage = 1;
		}
		if (pageSize == 0) {// 默认每页条数为10条记录
			pageSize = 10;
		}

		long totalCount = super.count(query, entityClass);
		// 计算总页数即总数量/每页条数
		int totalPage = (int) (totalCount / pageSize);
		if (totalCount % pageSize > 0) {
			totalPage++;
		}
		if (totalPage <= 0)
			totalPage = 1;
		// 实例化分页信息
		Page<T> page = new Page<T>(pageSize, currentPage, totalCount, totalPage);
		// 赋值查询列表
		if (items) {
			int skip = (currentPage - 1) * pageSize;
			query.skip(skip);
			query.limit(pageSize);
			List datas = super.find(query, entityClass);
			page.setItems(datas);
		}
		return page;
	}
}